#!/bin/bash

# 执行时间 0 0 */6 * * /var/node/n8n-work-flows/cron-task.sh >> /var/log/cron-task.log 2>&1

export PATH=/home/ubuntu/.nvm/versions/node/v20.19.2/bin:/usr/local/bin:/usr/bin:/bin

# 自动检测 node 和 pm2 路径
NODE_PATH=$(which node)
PM2_PATH=$(which pm2)

# 如果找不到 node 或 pm2，则退出并写日志
if [ -z "$NODE_PATH" ]; then
  echo "$(date) ERROR: Node.js not found in PATH" >> /var/log/cron-task.log
  exit 1
fi

if [ -z "$PM2_PATH" ]; then
  echo "$(date) ERROR: PM2 not found in PATH" >> /var/log/cron-task.log
  exit 1
fi

# 确保 PATH 包含 node 和 pm2
export PATH=$(dirname $NODE_PATH):$(dirname $PM2_PATH):$PATH

echo "$(date) INFO: Using node at $NODE_PATH" >> /var/log/cron-task.log
echo "$(date) INFO: Using pm2 at $PM2_PATH" >> /var/log/cron-task.log

# 删除文件
rm -f /var/node/n8n-work-flows/google/gmail-token.json
echo "$(date) INFO: Deleted /var/node/n8n-work-flows/google/gmail-token.json" >> /var/log/cron-task.log

# 暂停 pm2 服务
# $PM2_PATH stop all

# 重启 pm2 服务

$PM2_PATH restart app
# if [ $? -eq 0 ]; then
#   echo "$(date) INFO: PM2 restarted successfully" >> /var/log/cron-task.log
# else
#   echo "$(date) ERROR: PM2 restart failed" >> /var/log/cron-task.log
# fi

# 等待服务启动
sleep 20

# 访问接口
curl -s -o /dev/null -w "%{http_code}" http://localhost:5678/api/auth >> /var/log/cron-task.log 2>&1
echo " $(date) INFO: API request sent" >> /var/log/cron-task.log